package com.lzh.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.main.mapper.UserMapper;
import com.lzh.main.pojo.dto.Result;
import com.lzh.main.pojo.entity.User;
import com.lzh.main.service.UserAccountService;
import com.lzh.main.utils.JwtUtil;
import com.lzh.main.utils.UserDetailsImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserAccountServiceImpl implements UserAccountService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result register(String username, String password, String confirmPassword, String email) {
        //参数校验
        if (username == null || username.trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }

        if (email == null || email.trim().isEmpty()) {
            return Result.error("邮箱不能为空");
        }

        if (password == null || password.isEmpty()) {
            return Result.error("密码不能为空");
        }

        if (!password.equals(confirmPassword)) {
            return Result.error("两次输入的密码不一致");
        }

        // 邮箱格式校验
        if (!email.matches("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$")) {
            return Result.error("邮箱格式不正确");
        }

        // 用户名标准化处理
        username = username.trim().toLowerCase();
        email = email.trim().toLowerCase(); // 邮箱统一小写处理

        if (username.length() > 100) {
            return Result.error("用户名长度不能超过100字符");
        }

        if (username.matches("\\d+")) {
            return Result.error("用户名不能为纯数字");
        }

        // 密码复杂度校验
        if (password.length() < 8) {
            return Result.error("密码长度至少8位");
        }

        if (!password.matches("^(?=.*[A-Za-z])(?=.*\\d).+$")) {
            return Result.error("密码需包含字母和数字");
        }

        //--------------- 唯一性检查 ---------------
        QueryWrapper<User> usernameQuery = new QueryWrapper<>();
        usernameQuery.eq("username", username);
        if (userMapper.exists(usernameQuery)) {
            log.warn("注册失败：用户名 {} 已存在", username);
            return Result.error("用户名已存在");
        }

        QueryWrapper<User> emailQuery = new QueryWrapper<>();
        emailQuery.eq("email", email);
        if (userMapper.exists(emailQuery)) {
            log.warn("注册失败：邮箱 {} 已存在", email);
            return Result.error("邮箱已被注册");
        }

        //--------------- 用户对象创建 ---------------
        String encodedPassword = passwordEncoder.encode(password);
        User user = new User();
        user.setUsername(username);
        user.setPassword(encodedPassword);
        user.setEmail(email);
        user.setPhoto("https://www.helloimg.com/i/2024/12/22/6767fd5a3cf23.jpg");
        user.setLevel(1);
        user.setRating(1500);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        //--------------- 数据库操作 ---------------
        try {
            userMapper.insert(user);
        } catch (DuplicateKeyException e) {
            // 兜底处理（例如：高并发下唯一索引冲突）
            log.error("唯一索引冲突：{}", e.getMessage());
            if (e.getMessage().contains("username")) {
                return Result.error("用户名已存在");
            } else if (e.getMessage().contains("email")) {
                return Result.error("邮箱已被注册");
            }
            return Result.error("注册失败");
        }

        //--------------- 返回脱敏数据 ---------------
        Map<String, Object> safeUserData = new HashMap<>();
        safeUserData.put("id", user.getId());
        safeUserData.put("username", user.getUsername());
        safeUserData.put("email", user.getEmail());
        safeUserData.put("photo", user.getPhoto());
        log.info("用户 {} 注册成功，ID：{}", username, user.getId());
        return Result.success(safeUserData);
    }

    @Override
    public Result login(String account, String password) {
        // 参数校验
        if (account == null || account.trim().isEmpty()) {
            return Result.error("账号不能为空");
        }

        if (password == null || password.isEmpty()) {
            return Result.error("密码不能为空");
        }

        // 标准化处理
        account = account.trim().toLowerCase();

        // 判断是否为邮箱格式
        boolean isEmail = account.contains("@");

        // 根据账号类型进行查询
        QueryWrapper<User> query = new QueryWrapper<>();
        if (isEmail) {
            query.eq("email", account);
        } else {
            query.eq("username", account);
        }

        User user = userMapper.selectOne(query);

        // 用户不存在
        if (user == null) {
            log.warn("登录失败：账号 {} 不存在", account);
            return Result.error("账号不存在");
        }

        // 密码验证
        if (!passwordEncoder.matches(password, user.getPassword())) {
            log.warn("登录失败：账号 {} 密码错误", account);
            return Result.error("密码错误");
        }

        // 生成JWT
        String jwt = JwtUtil.createJWT(user.getId().toString());

        // 构建返回数据（用户信息和token）
        Map<String, Object> data = new HashMap<>();

        // 用户信息（脱敏）
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id", user.getId());
        userMap.put("username", user.getUsername());
        userMap.put("email", user.getEmail());
        userMap.put("photo", user.getPhoto());
        userMap.put("level", user.getLevel());
        userMap.put("rating", user.getRating());

        data.put("user", userMap);
        data.put("token", jwt);

        // 更新最后登录时间
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);

        log.info("用户 {} 登录成功", user.getUsername());
        return Result.success(data);
    }

    @Override
    public Result getUserInfo() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            if (authentication == null || !authentication.isAuthenticated()) {
                return Result.error("用户未登录");
            }

            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            User user = userDetails.getUser();

            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("photo", user.getPhoto());
            userInfo.put("rating", user.getRating());
            userInfo.put("level", user.getLevel());

            log.info("用户信息获取成功: {}", user.getUsername());
            return Result.success(userInfo);
        } catch (ClassCastException e) {
            log.error("用户信息解析失败: {}", e.getMessage());
            return Result.error("用户身份信息异常");
        } catch (Exception e) {
            log.error("系统异常: {}", e.getMessage());
            return Result.error("系统繁忙，请稍后重试");
        }
    }

    @Override
    public Result updateUserPhoto(Integer userId, String url) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        user.setPhoto(url);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
        log.info("用户{}头像已更新", user.getUsername());
        return Result.success(url);
    }

    @Override
    public Result updateUsername(Integer userId, String newUsername) {
        // 参数校验
        if (newUsername == null || newUsername.trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }

        // 用户名标准化处理
        newUsername = newUsername.trim().toLowerCase();

        if (newUsername.length() > 100) {
            return Result.error("用户名长度不能超过100字符");
        }

        if (newUsername.matches("\\d+")) {
            return Result.error("用户名不能为纯数字");
        }

        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 如果新用户名与当前用户名相同，直接返回成功
        if (user.getUsername().equals(newUsername)) {
            return Result.success(newUsername);
        }

        // 检查新用户名是否已存在
        QueryWrapper<User> usernameQuery = new QueryWrapper<>();
        usernameQuery.eq("username", newUsername);
        if (userMapper.exists(usernameQuery)) {
            log.warn("更新用户名失败：用户名 {} 已存在", newUsername);
            return Result.error("用户名已存在");
        }

        // 更新用户名
        user.setUsername(newUsername);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);

        log.info("用户ID {} 的用户名更新为 {}", userId, newUsername);
        return Result.success(newUsername);
    }
}
